package interfaz;

import clases.ClsDatabase;
import clases.ClsMetodos;
import javax.swing.JOptionPane;
/**
 *
 * @author mk
 */
public class dlgInsumoTipo extends javax.swing.JDialog {

    private ClsMetodos metodos=new ClsMetodos();
    private ClsDatabase bd=new ClsDatabase();
    /**
     * Creates new form dlg
     * @param parent
     * @param modal
     */
    public dlgInsumoTipo(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        this.setLocationRelativeTo(null);//Centramos la ventana
        _iniciar();
    }
//______________________________________________________________:)Soy una Bara Espaciadora
    // <editor-fold desc="TIPO DE INSUMOS CODE">
    //TIPO DE INSUMO
    public void _cargarTabla_TipoInsumo(){
        //String nombreBuscar=txtBuscarTI.getText().toString();
        metodos.tablaLlenaSql(tblTipoInsumo,
                "*",
                "FROM insumo_tipo "
                + "WHERE nombre like '%%' "
                + "ORDER BY orden asc");
    }

    public void EliminarTipoInsumo(){
        int fila=tblTipoInsumo.getSelectedRow();//Obtenemos la fila seleccionada
        if (fila!=-1) {
            //Confirmamos la eliminacion
            if (JOptionPane.showConfirmDialog(null, "Esta seguro de eliminar este Tipo de Insumo", "Mensaje", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE) == 0) {
                String id=tblTipoInsumo.getValueAt(fila, 0).toString();
                boolean seRepite=bd.verif_repite("SELECT nombre FROM insumo WHERE idinsumo_tipo='"+id+"'");
                if (!seRepite) {
                    boolean seElimino=bd.delete("insumo_tipo", "idinsumo_tipo='"+id+"'");
                    if (seElimino) {
                        _cargarTabla_TipoInsumo();
                        JOptionPane.showMessageDialog(null, "Se elimino el Tipo de Insumo con exito");
                    }
                }else{
                    JOptionPane.showMessageDialog(null, "No se puede eliminar este Tipo de Insumo, esta siendo usado!!!");
                }
            }            
        }else{
            JOptionPane.showMessageDialog(null, "Seleccione una fila!!!");
        }
    }

    public void upRow(){
        int fila=tblTipoInsumo.getSelectedRow();
//        System.err.println("up getSelectedRow-fila_"+fila);
//        System.err.println("up getSelectedRowCount_"+(fila-1));
        if (fila-1>=0) {
//            System.out.println("up");
            moverFilaJTable(fila,fila-1);
        }
    }

    public void downRow(){
        int fila=tblTipoInsumo.getSelectedRow();
//        System.err.println("down getSelectedRow-fila_"+fila);
//        System.err.println("down getSelectedRowCount_"+(tblTipoInsumo.getRowCount()-1));
        if (fila+1<=tblTipoInsumo.getRowCount()-1) {
//            System.out.println("down");
            moverFilaJTable(fila,fila+1);
        }
    }
    
    public void moverFilaJTable(int filaActual,int finalDestino){        
        if (filaActual!=-1 && tblTipoInsumo.getValueAt(filaActual, 3).toString().length()>0) {
//            System.out.println("moverFilaJTable");
            String idActual=tblTipoInsumo.getValueAt(filaActual, 0).toString();
            String id2=tblTipoInsumo.getValueAt(finalDestino, 0).toString();
            int ordenActual=Integer.parseInt(tblTipoInsumo.getValueAt(filaActual, 3).toString());
            int orden2=Integer.parseInt(tblTipoInsumo.getValueAt(finalDestino, 3).toString());
            //UPDATE Realizamos la consulta
            bd.update("insumo_tipo",
                    "orden='"+orden2+"' ",
                    "idinsumo_tipo='"+idActual+"'");

            bd.update("insumo_tipo",
                    "orden='"+ordenActual+"' ",
                    "idinsumo_tipo='"+id2+"'");
            _cargarTabla_TipoInsumo();
            tblTipoInsumo.setRowSelectionInterval(finalDestino, finalDestino);
        }
    }
    // </editor-fold>
//___________________________________________________________________________________ Soy una barra separadora :)
    // <editor-fold desc="CATEGORIA DE INSUMO CODE">
    //CATEGORIA DE INSUMO
    
    // </editor-fold>
    //___________________________________________________________________________________ Soy una barra separadora :)
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        body = new javax.swing.JPanel();
        jScrollPane2 = new javax.swing.JScrollPane();
        tblTipoInsumo = new javax.swing.JTable();
        btnEditar_TI = new javax.swing.JButton();
        btnUp = new javax.swing.JButton();
        btnDown = new javax.swing.JButton();
        jLabel11 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Tipo de Insumo");

        body.setBackground(new java.awt.Color(225, 235, 247));
        body.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        tblTipoInsumo.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null, null},
                {null, null, null, null, null},
                {null, null, null, null, null},
                {null, null, null, null, null},
                {null, null, null, null, null},
                {null, null, null, null, null},
                {null, null, null, null, null},
                {null, null, null, null, null}
            },
            new String [] {
                "ID", "Nombre", "Abreviatura", "Orden", "Estado"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false, true, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        tblTipoInsumo.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tblTipoInsumoMouseClicked(evt);
            }
        });
        jScrollPane2.setViewportView(tblTipoInsumo);

        body.add(jScrollPane2, new org.netbeans.lib.awtextra.AbsoluteConstraints(30, 30, 480, 150));

        btnEditar_TI.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resource/icon/principales/peque/editar.png"))); // NOI18N
        btnEditar_TI.setText("Editar");
        btnEditar_TI.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnEditar_TIActionPerformed(evt);
            }
        });
        body.add(btnEditar_TI, new org.netbeans.lib.awtextra.AbsoluteConstraints(30, 210, 90, -1));

        btnUp.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resource/icon/principales/peque/arriba.png"))); // NOI18N
        btnUp.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnUpActionPerformed(evt);
            }
        });
        body.add(btnUp, new org.netbeans.lib.awtextra.AbsoluteConstraints(540, 70, 30, 30));

        btnDown.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resource/icon/principales/peque/abajo.png"))); // NOI18N
        btnDown.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnDownActionPerformed(evt);
            }
        });
        body.add(btnDown, new org.netbeans.lib.awtextra.AbsoluteConstraints(540, 110, 30, 30));

        jLabel11.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resource/icon/principales/fondo_dialog.jpg"))); // NOI18N
        body.add(jLabel11, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 450, 260));

        getContentPane().add(body, java.awt.BorderLayout.CENTER);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnEditar_TIActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEditar_TIActionPerformed
        dlg_TipoInsumo dialogTI = new dlg_TipoInsumo(new javax.swing.JFrame(), true,this,tblTipoInsumo);
        //dialogTI.setTitle("Editando el Tipo de Insumo elegido");
        dialogTI.Editar();
    }//GEN-LAST:event_btnEditar_TIActionPerformed

    private void tblTipoInsumoMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tblTipoInsumoMouseClicked
        if (evt.getClickCount() == 2) {
            dlg_TipoInsumo dialogTI = new dlg_TipoInsumo(new javax.swing.JFrame(), true,this,tblTipoInsumo);
            //dialogTI.setTitle("Editando el Tipo de Insumo elegido");
            dialogTI.Editar();
        }
    }//GEN-LAST:event_tblTipoInsumoMouseClicked

    private void btnUpActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnUpActionPerformed
        upRow();
    }//GEN-LAST:event_btnUpActionPerformed

    private void btnDownActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDownActionPerformed
        downRow();
    }//GEN-LAST:event_btnDownActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(dlgInsumoTipo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(dlgInsumoTipo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(dlgInsumoTipo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(dlgInsumoTipo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the dialog */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                dlgInsumoTipo dialog = new dlgInsumoTipo(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    public javax.swing.JPanel body;
    private javax.swing.JButton btnDown;
    private javax.swing.JButton btnEditar_TI;
    private javax.swing.JButton btnUp;
    private javax.swing.JLabel jLabel11;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTable tblTipoInsumo;
    // End of variables declaration//GEN-END:variables
//______________________________________________________________:)Soy una Bara Espaciadora
   public void _iniciar() {
//        txtBuscarTI.setText("");
//        txtBuscarTI.requestFocus();
//        _cargarTabla_Unidades();
        _cargarTabla_TipoInsumo();
        //_cargarTabla_CategoriaInsumo();
        metodos.tablaOcultarcolumnas(tblTipoInsumo, new int[]{4});
    }


//______________________________________________________________:)Soy una Bara Espaciadora

}
